//
//  OrderDetailController.m
//  TCProject
//
//  Created by admin on 16/1/20.
//  Copyright © 2016年 wise-wing. All rights reserved.
//

#import "OrderDetailController.h"
#import "OrderManager.h"
#import "CAlertView.h"
#import "SelectCarView.h"
#import "CZCar.h"
#import "CZReasonController.h"
#import "AccountManager.h"
#import "ZDOrder.h"
#import "CZOrderDetailSignCell.h"
#import "CZServiceLogController.h"
#import "CZServiceLogInfoController.h"
#import <BaiduMapKit/BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>               //Component是一个包含那个framework所有头文件的文件
#import <BaiduMapAPI_Utils/BMKGeometry.h>
#import "UIImage+Rotate.h"
#import "CWStarRateView.h"
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <MapKit/MapKit.h>

#define MYBUNDLE_NAME @ "mapapi.bundle"
#define MYBUNDLE_PATH [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: MYBUNDLE_NAME]
#define MYBUNDLE [NSBundle bundleWithPath: MYBUNDLE_PATH]

@interface RouteAnnotation : BMKPointAnnotation
{
    int _type; ///<0:起点 1：终点 2：公交 3：地铁 4:驾乘 5:途经点
    int _degree;
}

@property (nonatomic) int type;
@property (nonatomic) int degree;
@end

@implementation RouteAnnotation

@synthesize type = _type;
@synthesize degree = _degree;
@end

@interface OrderDetailController ()<BMKMapViewDelegate,BMKRouteSearchDelegate,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) OrderManager *manager;
@property (nonatomic, weak) UITableView *tableView;

@property (nonatomic, strong) CAlertView *alertView;
@property (nonatomic, weak) SelectCarView *carView;
@property (nonatomic, strong) CZCar *rushCar;

@property (nonatomic, strong) BMKRouteSearch *routesearch;

@property (nonatomic, strong) BMKLocationService *locService;

#pragma mark --- orderDetailSignHeaderView   订单详情签收头部视图
@property (weak, nonatomic) IBOutlet UILabel *th1;
@property (weak, nonatomic) IBOutlet UILabel *th2;
@property (weak, nonatomic) IBOutlet UILabel *th4;

@property (weak, nonatomic) IBOutlet UILabel *th3;
@property (weak, nonatomic) IBOutlet UIView *topContainerView;

#pragma mark -- top Container
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topContainerBottomConstraint;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;

@property (weak, nonatomic) IBOutlet UILabel *hint1Label;
@property (weak, nonatomic) IBOutlet UILabel *hint2Label;
@property (weak, nonatomic) IBOutlet UILabel *label1;
@property (weak, nonatomic) IBOutlet UILabel *label2;
@property (weak, nonatomic) IBOutlet UILabel *label5;
@property (weak, nonatomic) IBOutlet UILabel *label3;
@property (weak, nonatomic) IBOutlet UILabel *label4;
@property (weak, nonatomic) IBOutlet UILabel *hint4Label;
@property (weak, nonatomic) IBOutlet UIView *middleContainerView;

#pragma mark -- 中部视图
@property (weak, nonatomic) IBOutlet UILabel *cl1;
@property (weak, nonatomic) IBOutlet UILabel *cl2;
@property (weak, nonatomic) IBOutlet UILabel *cl3;
@property (weak, nonatomic) IBOutlet UILabel *cl4;


@property (weak, nonatomic) IBOutlet UIButton *orderButton;
@property (weak, nonatomic) IBOutlet BMKMapView *mapView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *mapViewtopConstaint;
- (IBAction)showAll:(id)sender;

#pragma mark -- 底部视图
@property (weak, nonatomic) IBOutlet UIView *bottomContainerView;

@property (weak, nonatomic) IBOutlet UIView *leftView;

@property (weak, nonatomic) IBOutlet UIView *rightView;
@property (weak, nonatomic) IBOutlet UIButton *bigCallButton;

@property (weak, nonatomic) IBOutlet UIButton *rushButton;
- (IBAction)rushAction:(id)sender;

- (IBAction)callAction:(id)sender;

#pragma mark --- 评价视图 

@property (weak, nonatomic) IBOutlet UILabel *dpLabel;

@property (weak, nonatomic) IBOutlet UILabel *dcLabel;
@property (weak, nonatomic) IBOutlet CWStarRateView *ratingView;
@property (weak, nonatomic) IBOutlet UILabel *dContent;

@end

@implementation OrderDetailController
- (IBAction)addServiceAction:(id)sender {
    CZServiceLogInfoController *logInfoVC = [self.storyboard instantiateViewControllerWithIdentifier:@"logInfoVC"];
    logInfoVC.order = _order;
   
    [self showViewController:logInfoVC sender:nil];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.cl1.adjustsFontSizeToFitWidth = YES;
    self.cl2.adjustsFontSizeToFitWidth = YES;
    self.cl3.adjustsFontSizeToFitWidth = YES;
    self.cl4.adjustsFontSizeToFitWidth = YES;
    
    self.manager = [OrderManager new];
    _routesearch = [[BMKRouteSearch alloc]init];

    [[AccountManager sharedInstance] updateLocation];
    
   // NSLog(@"%f",self.mapView.centerCoordinate.latitude);//39.914884
    
//    _locService = [[BMKLocationService alloc] init];
//    [_locService startUserLocationService];
    self.navigationItem.title = @"订单详情";
    
    [self getData];

}


- (void)getData
{
    [self showHudWithhint:kDefaultMessage];
    [self.manager getOwnerOrderDetail:_order own:_isOwn complete:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            [self.tableView removeFromSuperview];
            self.order = response.result;
            [self setupInfo];
            if (_order.statusId > ZDOwnerStatusServiceLog && _order.statusId <= ZDOwnerStatusCommented) {   //订单在+服务记录和已评价之间
                [self getServiceLogs];
            } else if (_order.statusId == ZDOwnerStatusUnEnd) {    //未完成（全部结算未勾选）
                [self getServiceLogs];
            }
        } else {
            [self showHint:@"获取订单详情失败"];
        }
    }];
}


/** 如果成功响应，做如下操作 */
- (void)setupInfo                   //创建信息，给界面的控件赋值
{
    
    [self.tableView removeFromSuperview];
    
    [self.orderButton setTitle:[NSString stringWithFormat:@"订单号：%@", _order.orderNum] forState:UIControlStateNormal];
    self.priceLabel.text = [NSString stringWithFormat:@"￥%.2f", _order.sumPrice];
    self.label1.text = _order.appointmentTime;
    self.label2.text = [NSString stringWithFormat:@"%.1f方", _order.volume];
    self.label3.text = [NSString stringWithFormat:@"%@(%ld辆)", _order.style1, _order.count];
    self.hint4Label.text = [NSString stringWithFormat:@"%@：", _order.conditionName];
    self.label4.text = _order.condition;
    self.cl1.text = [NSString stringWithFormat:@"站点名称：%@", _order.stationName];
    self.cl2.text = [NSString stringWithFormat:@"站点地址：%@", _order.address];
    if ([BMUtils isEmptyString:_order.disName]) {
        self.cl3.text = [@"联系人：" stringByAppendingFormat:@"（%@）", _order.disPhone];
    } else {
        self.cl3.text = [NSString stringWithFormat:@"联系人：%@(%@)", _order.disName, _order.disPhone];
    }
    self.cl4.text = [NSString stringWithFormat:@"备注信息：%@", [BMUtils isEmptyString:_order.remarks] ? @"无" : _order.remarks];
    //NSLog(@"%@------%@---------%@-------cl4=%@",_cl1.text,_cl2.text,_cl3.text,_cl4.text);
    
    double singlePrice = _order.sumPrice / _order.volume;
    self.label5.text = [NSString stringWithFormat:@"%.1f元/方", singlePrice];
    
    if (_order.statusId > ZDOwnerStatusRush && _order.statusId < ZDOwnerStatusCancel) {   //待抢单 与 取消订单之间
        double price = _order.sumPrice / _order.count;
        self.priceLabel.text = [NSString stringWithFormat:@"￥%.2f", price];
    }
    
    if (_order.statusId == 0) {
        _order.statusId = ZDOwnerStatusRush;
    }
    
    [self setupDriverLine];
    
    ZDOwnerStatus status = _order.statusId;
    
    [self setupRightButton];
    switch (status) {
        case ZDOwnerStatusRush:     //待抢单
            self.leftView.hidden = self.rightView.hidden = self.bigCallButton.hidden = YES;
            //            if (_order.status != ZDOrderStatusRush) {
            //                self.rushButton.enabled = NO;
            //                [self.rushButton setTitle:@"人员已满" forState:UIControlStateDisabled];
            //            }
            break;
        case ZDOwnerStatusRushSuccess:     //抢单成功
            self.rushButton.enabled = NO;
            break;
        case ZDOwnerStatusGP:      //订单改派中
            self.rushButton.enabled = NO;
            break;
        case ZDOwnerStatusDZ:       //到站
            self.leftView.hidden = self.rightView.hidden = NO;
            [self.rushButton setTitle:@"到站" forState:UIControlStateNormal];
            if ([@"汽泵" isEqualToString:_order.style1] || [@"车载泵" isEqualToString:_order.style1]) {
                [self.rushButton setTitle:@"到工地" forState:UIControlStateNormal];
            }
            break;
        case ZDOwnerStatusCancel:      //取消订单
        case ZDOwnerStatusCancel1:      //取消订单   11
        case ZDOwnerStatusCancel2:      //取消订单（被处罚24小时内不允许抢单） 12
        case ZDOwnerStatusRepeal:       //订单已撤销（获得赔偿金）
        case ZDOwnerStatusClose:        //订单关闭
        case ZDOwnerStatusGPSuccess:    //改派成功
            [self cancleOrder];
            break;
        case ZDOwnerStatusServiceLog:   //+服务记录
        case ZDOwnerStatusWaitSign:     //待签收
        case ZDOwnerStatusWaitWind:     //待结算
        case ZDOwnerStatusEnded:        //已完成
        case ZDOwnerStatusUnEnd:        //未完成（全部结算未勾选）
            [self setupWithSignLog:status];
            break;
        case ZDOwnerStatusCommented:    //已评价
            [self setDiscuss];
            break;
        default:
            break;
    }
    
    if (status == ZDOwnerStatusServiceLog || status == ZDOwnerStatusWaitSign) {
        //        self.rushButton.titleLabel.numberOfLines = 0;
        //        self.rushButton.titleLabel.textAlignment = NSTextAlignmentCenter;
        //        NSMutableAttributedString *attrs = [[NSMutableAttributedString alloc] initWithString:@"+\n服务记录\n"];
        //        [attrs addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:24.f] range:NSMakeRange(0, 1)];
        //        [attrs addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:11.f] range:NSMakeRange(2, 4)];
        //        [self.rushButton setAttributedTitle:attrs forState:UIControlStateNormal];
        self.rushButton.titleLabel.font = [UIFont systemFontOfSize:13];
        [self.rushButton setTitle:@"结束服务" forState:UIControlStateNormal];
    } else if (status == ZDOwnerStatusGP) {
        self.rushButton.titleLabel.numberOfLines = 0;
        self.rushButton.titleLabel.textAlignment = NSTextAlignmentCenter;
        NSMutableAttributedString *attrs = [[NSMutableAttributedString alloc] initWithString:@"订单\n改派中"];
        [attrs addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:12.f] range:NSMakeRange(0, 2)];
        [attrs addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:13.f] range:NSMakeRange(3, 3)];
        [self.rushButton setAttributedTitle:attrs forState:UIControlStateDisabled];
    }
    if (status == ZDOwnerStatusServiceLog || status == ZDOwnerStatusWaitSign || status == ZDOwnerStatusWaitWind || status == ZDOwnerStatusUnEnd) {
        self.priceLabel.hidden = YES;
    }
}

- (void)cancleOrder         //改派成功进行调用
{
    //    self.priceLabel.hidden = YES;
    self.middleContainerView.hidden = self.bottomContainerView.hidden = YES;
    //    self.priceLabel.hidden = YES;
    self.hint1Label.text = @"站点名称：";
    self.hint2Label.text = @"取消时间：";
    self.label1.text = _order.stationName;
    
    CGFloat offset = CGRectGetHeight(self.topContainerView.bounds) - CGRectGetMaxY(self.hint2Label.frame);
    self.topContainerBottomConstraint.constant -= offset;
    self.topContainerView.clipsToBounds = YES;
    
    switch (_order.statusId) {
        case ZDOwnerStatusCancel:
        case ZDOwnerStatusCancel1:
        case ZDOwnerStatusCancel2:
            self.label2.text = [NSString stringWithFormat:@"%@ (车主取消)", _order.operateDate];
            break;
        case ZDOwnerStatusRepeal:
            self.label2.text = [NSString stringWithFormat:@"%@ (站点取消)", _order.operateDate];
            //            self.priceLabel.hidden = NO;
            //            self.priceLabel.text = [NSString stringWithFormat:@"获赔%@元", _order.damage];
            break;
        case ZDOwnerStatusClose:
            self.label2.text = [NSString stringWithFormat:@"%@ (站点关闭)", _order.operateDate];
            break;
        default:
            break;
    }
}

- (void)setupWithSignLog:(ZDOwnerStatus)status    //未完成（全部结算未勾选） 时调用
{
    self.rightView.hidden = YES;
    self.bigCallButton.hidden = NO;
    [self.rushButton setTitle:@"结束服务" forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = nil;
    
    if (status == ZDOwnerStatusWaitSign || status == ZDOwnerStatusServiceLog || status == ZDOwnerStatusUnEnd) {//如果状态为待签收，+服务记录和未完成  
        self.leftView.hidden = YES;
    }
    
         else if (status == ZDOwnerStatusEnded || status == ZDOwnerStatusWaitWind) { //如果订单状态为已完成和等待结算时调用
         self.bottomContainerView.hidden = YES;
         }
    
    self.leftView.hidden = YES;
    if (_order.checked == 1) {
        self.bottomContainerView.hidden = YES;
    } else {
        self.bottomContainerView.hidden = NO;
    }
    
    self.middleContainerView.hidden = YES;
    
    UITableView *tableView = [[UITableView alloc] init];//放订单详情签收cell
    [tableView registerNib:[UINib nibWithNibName:@"CZOrderDetailSignCell" bundle:nil] forCellReuseIdentifier:reuseIdentifier];
    tableView.backgroundColor = [UIColor clearColor];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.rowHeight = 125.f;
    [self.view insertSubview:tableView aboveSubview:_bottomContainerView];
    self.tableView = tableView;
    
    CGFloat y = CGRectGetMaxY(_topContainerView.frame) + 10;
    if (status == ZDOwnerStatusEnded) {  //如果用户状态为已完成
        CGFloat offset = CGRectGetHeight(self.topContainerView.bounds) - CGRectGetMaxY(self.hint2Label.frame);
        self.topContainerBottomConstraint.constant -= offset;
        self.topContainerView.clipsToBounds = YES;
        CGRect rect = [self.topContainerView convertRect:_hint2Label.frame toView:self.view];
        y = CGRectGetMaxY(rect) + 10;
    }
    
    CGFloat height = 0;
    //    if (status == ZDOwnerStatusWaitWind || status == ZDOwnerStatusEnded) {
    if (_order.checked == 1) {
        height = kScreenHeight - y;
    } else {
        height = kScreenHeight - y - CGRectGetHeight(_bottomContainerView.bounds);
    }
    tableView.frame = CGRectMake(10.f, y, kScreenWidth - 20.f, height);
    
    if (status != ZDOwnerStatusEnded) {
        UIView *topView = [[NSBundle mainBundle] loadNibNamed:@"OrderDetailSignHeaderView" owner:self options:nil].firstObject;
        topView.clipsToBounds = YES;
        
        if (!_order.checked) {
            topView.height = 170.f;
        } else {
            topView.height = 120.f;
        }
        tableView.tableHeaderView = topView;
        
        _th1.text = [NSString stringWithFormat:@"站点名称：%@", _order.stationName];
        _th2.text = [NSString stringWithFormat:@"站点地址：%@", _order.address];
        //        _th3.text = [NSString stringWithFormat:@"联系人：%@(%@)", _order.disName, _order.disPhone];
        if ([BMUtils isEmptyString:_order.disName]) {
            self.th3.text = [@"联系人：" stringByAppendingFormat:@"（%@）", _order.disPhone];
        } else {
            self.th3.text = [NSString stringWithFormat:@"联系人：%@(%@)", _order.disName, _order.disPhone];
        }
        _th4.text = [NSString stringWithFormat:@"备注信息：%@", [BMUtils isEmptyString:_order.remarks] ? @"无" : _order.remarks];
    } else {
        self.hint1Label.text = @"站点名称：";
        self.hint2Label.text = @"运输方量：";
        _label1.text = _order.stationName;
    }
        self.priceLabel.text = [NSString stringWithFormat:@"￥%.1f", _order.totalRealSumPrice];
}

- (void)setDiscuss   //已评价  进行调用
{
    self.priceLabel.hidden = YES;
    UIView *disbussView = [[NSBundle mainBundle] loadNibNamed:@"CZDiscussView" owner:self options:nil].firstObject;
    [self.view addSubview:disbussView];
    [disbussView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_topContainerView.mas_bottom);
        make.left.mas_equalTo(self.view).offset(10);
        make.right.mas_equalTo(self.view).offset(10);
        make.bottom.mas_equalTo(self.view);
    }];
    
    self.middleContainerView.hidden = self.bottomContainerView.hidden = YES;
    CGFloat offset = CGRectGetHeight(self.topContainerView.bounds) - CGRectGetMaxY(self.hint1Label.frame) - 5;
    self.topContainerBottomConstraint.constant -= offset;
    self.topContainerView.clipsToBounds = YES;
    
    self.hint1Label.text = @"站点名称：";
    self.label1.text = _order.stationName;
    self.ratingView.userInteractionEnabled = NO;
}


/** 如果订单在+服务记录和已评价之间 */
- (void)getServiceLogs
{
    BMRequest *request = [BMRequest requestWithPath:@"getMyServices.htm" contentKey:@"serviceLogs"];
    request.params = @{@"ownerId": @([AccountManager sharedInstance].user.ID), @"orderId": @(_order.ID),  @"pageNo": @1, @"pageSize": @100000};
    [ServiceLog postWithRequest:request finish:^(BMResponse *response, NSError *error) {
        if (response.status == kResultOK) {
            _order.serviceLogs = response.result;
            [self setServieLogInfo];                    //
        } else if (response.status == 2) {
            [self showHint:@"暂无服务记录"];
        } else {
            [self showHint:@"获取服务记录失败"];
        }
    }];
    
}

- (void)setServieLogInfo               //设置服务记录信息
{
    double sumPrice = 0;
    double sumVolume = 0;
    for (int i = 0; i < _order.serviceLogs.count; i++) {
        ServiceLog *log = _order.serviceLogs[i];
        sumPrice += log.realsumPrice;
        sumVolume +=  log.volume;
    }
    if (_order.statusId == ZDOwnerStatusCommented) {    //用户状态为已完成
                self.dpLabel.text = [NSString stringWithFormat:@"￥%.1f", sumPrice];
                self.dcLabel.text = [NSString stringWithFormat:@"%.1f方", sumVolume];
                self.ratingView.scorePercent = [_order.score doubleValue] / 10;
                self.dContent.text = _order.content;
    } else {
        self.priceLabel.text = [NSString stringWithFormat:@"￥%.1f", sumPrice];
        [self.tableView reloadData];
    }
    if (_order.statusId == ZDOwnerStatusEnded) {
        self.label2.text = [NSString stringWithFormat:@"%.1f方", sumVolume];
    }
}

/** 如果用户状态为  未完成（全部结算未勾选）*/
//做和上面相同的操作


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"reasonSegue"]) {
        CZReasonController *reasonVC = segue.destinationViewController;//CZ 车主
        reasonVC.order = _order;
    }
}


/** 抢单点击事件  */
- (IBAction)rushAction:(id)sender {
    //NSLog(@"%@",self.rushButton.currentTitle);//订单号：T20160120244268
    ZDOwnerStatus status = _order.statusId;
    if (status == ZDOwnerStatusRush) {        //待抢单
        [self rushTask:_order];
    } else if (status == ZDOwnerStatusDZ) {   //到站
//                CLLocationDistance dis = BMKMetersBetweenMapPoints(BMKMapPointForCoordinate([AccountManager sharedInstance].location), BMKMapPointForCoordinate(CLLocationCoordinate2DMake(_order.latitude, _order.longitude)));
//                if (dis > 1000) {
//                    [self showHint:@"距离站点大于1km不能到站"];
//                    return;
//                }
        [self toZhanTask];
    } else if (_order.checked == 0) {    //check：是否同时确认整个订单服务结束（0）
        if (_order.serviceLogs.count) {
            [self finishServieTask];
        } else {
            [self showHint:@"请添加服务记录"];
        }
    }

}

/** 如果用户状态为 待抢单  执行以下操作*/
- (void)rushTask:(CZOrder *)order                      //抢单任务
{
    
    if (![AccountManager sharedInstance].isLogin) {
        UIViewController *loginVC = [self.storyboard instantiateViewControllerWithIdentifier:@"loginVC"];
        [self presentViewController:loginVC animated:YES completion:nil];
        return;
    }
    
    BMRequest *request = [BMRequest requestWithPath:@"robOrder.htm" contentKey:@"availableTrucks"];
    if (_rushCar) {
        request.params = @{@"orderId": @(order.ID), @"ownerId": @([AccountManager sharedInstance].user.ID), @"truckId": @(_rushCar.ID), @"phone": [AccountManager sharedInstance].user.phone};
    } else {
        request.params = @{@"orderId": @(order.ID), @"ownerId": @([AccountManager sharedInstance].user.ID), @"phone": [AccountManager sharedInstance].user.phone};
    }
    [self showHudWithhint:kDefaultMessage];
    [CZCar postWithRequest:request finish:^(BMResponse *response, NSError *error) {
        [self hideHud];
        self.rushCar = nil;
        if (response.status == kResultOK) {
            _isOwn = YES;
            [self getData];
            [self showHint:@"抢单成功"];
        } else if (response.status == 4) {//该订单的用车时间前后2小时有未完成的订单,常常返回这个
            [self showHint:response.msg];
            
        } else if (response.status == 5) {
            if ([response.result count] == 0) {//用户没有可用车辆
                UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:response.msg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                [alertVC addAction:cancleAction];
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"现在去添加" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    UIViewController *carVC = [self.storyboard instantiateViewControllerWithIdentifier:@"carInfo"];
                    [self showViewController:carVC sender:nil];
                }];
                [alertVC addAction:okAction];
                [cancleAction setValue:kGlobalColor forKeyPath:@"titleTextColor"];
                [okAction setValue:kGlobalColor forKeyPath:@"titleTextColor"];
                [self presentViewController:alertVC animated:YES completion:nil];
            } else {
                [self.alertView show];
                self.carView.cars = response.result;
                [self.carView.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
            }
        } else {
            if (error) {
                [self showHint:@"抢单失败"];
            } else {
                [self showHint:response.msg];
                           }
        }
    }];
}

/**
 *  到站
 */
- (void)toZhanTask
{
    BMRequest *request = [BMRequest requestWithPath:@"orderLog/update.htm"];
    request.params = @{@"orderId": @(_order.ID), @"ownerId": @([AccountManager sharedInstance].user.ID)};
    [self showHudWithhint:kDefaultMessage];
    [[BMHttpTool sharedInstance] postWith:request finish:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            [self getData];
        } else {
            [self showHint:response.msg];
        }
    }];
}

/** 是否同时确认整个订单服务结束（0）做如下操作 */
- (void)finishServieTask                //完成服务
{
    BMRequest *request = [BMRequest requestWithPath:@"finishService.htm"];
    request.params = @{@"orderId": @(_order.ID), @"ownerId": @([AccountManager sharedInstance].user.ID), @"checked": @1};
    [[BMHttpTool sharedInstance] postWith:request finish:^(BMResponse *response, NSError *error) {
        if (response.status == kResultOK) {
            [self getData];
        } else {
            [self showHint:@"结束服务失败"];
        }
    }];
}




/** callbutton被点击后的操作 */
- (IBAction)callAction:(id)sender {
    [BMUtils callWithPhoneNumber:_order.disPhone];
}




- (CAlertView *)alertView
{
    if (!_alertView) {
        SelectCarView *carView = [[NSBundle mainBundle] loadNibNamed:@"SelectCarView" owner:self options:nil].firstObject;
        _alertView = [[CAlertView alloc] initWithView:carView];
        self.carView = carView;
    }
    return _alertView;
}

- (NSTimer *)timer
{
    if (!_timer) {
        _timer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(fireRrfresh) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
    }
    return _timer;
}

- (void)fireRrfresh
{
    [self showHint:@"refresh"];
    [self getData];
}






- (void)setupRightButton
{
    if (_order.statusId == ZDOwnerStatusRushSuccess || _order.statusId == ZDOwnerStatusDZ) {
        UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"改派订单" style:UIBarButtonItemStylePlain target:self action:@selector(GPAction)];
        [item setTitleTextAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12.f], NSForegroundColorAttributeName: [UIColor whiteColor]} forState:UIControlStateNormal];
        self.navigationItem.rightBarButtonItem = item;
    } else {
        self.navigationItem.rightBarButtonItem = nil;
    }
}


/**
 *  改派订单
 */
- (void)GPTask
{
    BMRequest *request = [BMRequest requestWithPath:@"changeOrder.htm"];
    request.params = @{@"orderId": @(_order.ID), @"ownerId": @([AccountManager sharedInstance].user.ID)};
    [self showHudWithhint:kDefaultMessage];
    [[BMHttpTool sharedInstance] postWith:request finish:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            _order.statusId = ZDOwnerStatusGP;
            [self setupInfo];
        } else {
            [self showHint:@"改派订单失败"];
        }
    }];
}



- (void)updateServiceLog
{
    [self getServiceLogs];
}


#pragma mark ---- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _order.serviceLogs.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CZOrderDetailSignCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    cell.log = _order.serviceLogs[indexPath.row];
    cell.order = _order;
    return cell;
  
}

#pragma mark --- UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CZServiceLogController *logVC = [CZServiceLogController new];
    logVC.order = _order;
    [self showViewController:logVC sender:nil];
    
}

//- (IBAction)cancleAction:(id)sender {
//    [self.alertView dismissAlertViewWithAnimated:YES];
//}

//
//- (IBAction)okAction:(UIButton *)sender {
//    NSIndexPath *indexPath = [self.carView.tableView indexPathForSelectedRow];
//    if (indexPath) {
//        [self.alertView dismissAlertViewWithAnimated:YES];
//        self.rushCar = self.carView.cars[indexPath.row];
//        [self rushTask:_order];
//    }
//}




/** showAll Button被点击以后 */
- (IBAction)showAll:(id)sender {
    UILayoutPriority priority = _mapViewtopConstaint.priority;
    if (priority == 800) {
        _mapViewtopConstaint.priority = 700;
       
    } else {
        _mapViewtopConstaint.priority = 800;
      
    }
    
    [UIView animateWithDuration:kDefaultAnimDuration animations:^{
        [self.middleContainerView setNeedsLayout];
        [self.middleContainerView layoutIfNeeded];
    }];

}

#pragma mark --- 百度地图
///**
// *用户位置更新后，会调用此函数
// *@param userLocation 新的用户位置
// */
//- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
//{
//    
//    BMKCoordinateRegion region;
//    region.center.latitude = userLocation.location.coordinate.latitude;
//    region.center.longitude = userLocation.location.coordinate.longitude;
//    region.span.latitudeDelta = 0.2;
//    region.span.latitudeDelta = 0.2;
//    if (_mapView) {
//        _mapView.region = region;
//       // NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
//        
//    }
//    
//    // _mapView.showsUserLocation = YES;
//    [_mapView updateLocationData:userLocation];
//}

-(void)viewWillAppear:(BOOL)animated {
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    _routesearch.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    
//    _locService.delegate = self;
//    
//    _mapView.mapType = BMKUserTrackingModeNone;
//    _mapView.zoomLevel = 16;
    
  //  _mapView.showsUserLocation = NO;//先关闭显示的定位图层
   // _mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
    //_mapView.showsUserLocation = YES;//显示定位图层
    
 //   [self.timer setFireDate:[NSDate dateWithTimeIntervalSinceNow:5]];
}

-(void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    _routesearch.delegate = nil; // 不用时，置nil
    
   // _locService.delegate = nil;
   // self.timer.fireDate = [NSDate distantFuture];
}

- (void)dealloc {
    if (_routesearch != nil) {
        _routesearch = nil;
    }
    if (_mapView) {
        _mapView = nil;
    }
}

- (void) setupDriverLine
{
    BMKPlanNode*startP = [[BMKPlanNode alloc]init];
    startP.pt = [AccountManager sharedInstance].location;
    NSLog(@"%f %f",startP.pt.latitude,startP.pt.longitude);
    BMKPlanNode*endP = [[BMKPlanNode alloc]init];
    NSLog(@"---------------------------");

    endP.pt = CLLocationCoordinate2DMake(_order.latitude, _order.longitude);
     NSLog(@"%f %f",endP.pt.latitude,endP.pt.longitude);
    BMKDrivingRoutePlanOption *drivingRouteSearchOption = [[BMKDrivingRoutePlanOption alloc]init];
    drivingRouteSearchOption.from = startP;
    drivingRouteSearchOption.to = endP;
    BOOL flag = [_routesearch drivingSearch:drivingRouteSearchOption];
    if(flag)
    {
        NSLog(@"car检索发送成功");
    }
    else
    {
        NSLog(@"car检索发送失败");
    }
}

- (void)onGetDrivingRouteResult:(BMKRouteSearch*)searcher result:(BMKDrivingRouteResult*)result errorCode:(BMKSearchErrorCode)error
{
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == BMK_SEARCH_NO_ERROR) {
        BMKDrivingRouteLine* plan = (BMKDrivingRouteLine*)[result.routes objectAtIndex:0];
        // 计算路线方案中的路段数目
        NSInteger size = plan.steps.count;
        int planPointCounts = 0;
        for (int i = 0; i < size; i++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:i];
            if(i==0){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.starting.location;
                item.title = @"起点";
                item.type = 0;
                [_mapView addAnnotation:item]; // 添加起点标注
                
            }else if(i == size - 1){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.terminal.location;
                item.title = @"终点";
                item.type = 1;
                [_mapView addAnnotation:item]; // 添加起点标注
            }
            
            //添加annotation节点
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = transitStep.entrace.location;
            item.title = transitStep.entraceInstruction;
            item.degree = transitStep.direction * 30;
            
            item.type = 4;
            [_mapView addAnnotation:item];
            
            //轨迹点总数累计
            planPointCounts += transitStep.pointsCount;
        }
        // 添加途经点
        if (plan.wayPoints) {
            for (BMKPlanNode* tempNode in plan.wayPoints) {
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item = [[RouteAnnotation alloc]init];
                item.coordinate = tempNode.pt;
                item.type = 5;
                item.title = tempNode.name;
                [_mapView addAnnotation:item];
            }
        }
        //轨迹点
        BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts];
        int i = 0;
        for (int j = 0; j < size; j++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:j];
            int k=0;
            for(k=0;k<transitStep.pointsCount;k++) {
                temppoints[i].x = transitStep.points[k].x;
                temppoints[i].y = transitStep.points[k].y;
                i++;
            }
            
        }
        // 通过points构建BMKPolyline
        BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
        [_mapView addOverlay:polyLine]; // 添加路线overlay
        delete []temppoints;
        [self mapViewFitPolyLine:polyLine];
        
        if (size == 1) {
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = CLLocationCoordinate2DMake(_order.latitude, _order.longitude);
            item.title = @"终点";
            item.type = 1;
            [_mapView addAnnotation:item]; // 添加起点标注
        }
    }
}

- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[RouteAnnotation class]]) {
        return [self getRouteAnnotationView:view viewForAnnotation:(RouteAnnotation*)annotation];
    }
    return nil;
}

- (BMKOverlayView*)mapView:(BMKMapView *)map viewForOverlay:(id<BMKOverlay>)overlay
{
    if ([overlay isKindOfClass:[BMKPolyline class]]) {
        BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
        polylineView.fillColor = [[UIColor cyanColor] colorWithAlphaComponent:1];
        polylineView.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:0.7];
        polylineView.lineWidth = 3.0;
        return polylineView;
    }
    return nil;
}

- (BMKAnnotationView*)getRouteAnnotationView:(BMKMapView *)mapview viewForAnnotation:(RouteAnnotation*)routeAnnotation
{
    BMKAnnotationView* view = nil;
    switch (routeAnnotation.type) {
        case 0:
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"start_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"start_node"];
                view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_start.png"]];
                view.centerOffset = CGPointMake(0, -(view.frame.size.height * 0.5));
                view.canShowCallout = TRUE;
            }
            view.annotation = routeAnnotation;
        }
            break;
        case 1:
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"end_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"end_node"];
                view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_end.png"]];
                view.centerOffset = CGPointMake(0, -(view.frame.size.height * 0.5));
                view.canShowCallout = TRUE;
            }
            view.annotation = routeAnnotation;
        }
            break;
        case 2:
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"bus_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"bus_node"];
                view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_bus.png"]];
                view.canShowCallout = TRUE;
            }
            view.annotation = routeAnnotation;
        }
            break;
        case 3:
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"rail_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"rail_node"];
                view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_rail.png"]];
                view.canShowCallout = TRUE;
            }
            view.annotation = routeAnnotation;
        }
            break;
        case 4:
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"route_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"route_node"];
                view.canShowCallout = TRUE;
            } else {
                [view setNeedsDisplay];
            }
            
            UIImage* image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_direction.png"]];
            view.image = [image imageRotatedByDegrees:routeAnnotation.degree];
            view.annotation = routeAnnotation;
            
        }
            break;
        case 5:
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"waypoint_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"waypoint_node"];
                view.canShowCallout = TRUE;
            } else {
                [view setNeedsDisplay];
            }
            
            UIImage* image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_waypoint.png"]];
            view.image = [image imageRotatedByDegrees:routeAnnotation.degree];
            view.annotation = routeAnnotation;
        }
            break;
        default:
            break;
    }
    
    return view;
}

- (NSString*)getMyBundlePath1:(NSString *)filename
{
    
    NSBundle * libBundle = MYBUNDLE ;
    if ( libBundle && filename ){
        NSString * s=[[libBundle resourcePath ] stringByAppendingPathComponent : filename];
        return s;
    }
    return nil ;
}

//根据polyline设置地图范围
- (void)mapViewFitPolyLine:(BMKPolyline *) polyLine {
    CGFloat ltX, ltY, rbX, rbY;
    if (polyLine.pointCount < 1) {
        return;
    }
    BMKMapPoint pt = polyLine.points[0];
    ltX = pt.x, ltY = pt.y;
    rbX = pt.x, rbY = pt.y;
    for (int i = 1; i < polyLine.pointCount; i++) {
        BMKMapPoint pt = polyLine.points[i];
        if (pt.x < ltX) {
            ltX = pt.x;
        }
        if (pt.x > rbX) {
            rbX = pt.x;
        }
        if (pt.y > ltY) {
            ltY = pt.y;
        }
        if (pt.y < rbY) {
            rbY = pt.y;
        }
    }
    BMKMapRect rect;
    rect.origin = BMKMapPointMake(ltX , ltY);
    rect.size = BMKMapSizeMake(rbX - ltX, rbY - ltY);
    [_mapView setVisibleMapRect:rect];
    _mapView.zoomLevel = _mapView.zoomLevel - 0.3;
}

//#pragma mark -- 百度地图Location
///**
// *在地图View将要启动定位时，会调用此函数
// *@param mapView 地图View
// */
//- (void)willStartLocatingUser
//{
//    NSLog(@"start locate");
//}
//
///**
// *用户方向更新后，会调用此函数
// *@param userLocation 新的用户位置
// */
//- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
//{
//    [_mapView updateLocationData:userLocation];
//    NSLog(@"heading is %@",userLocation.heading);
//}
//
///**
// *在地图View停止定位后，会调用此函数
// *@param mapView 地图View
// */
//- (void)didStopLocatingUser
//{
//    NSLog(@"stop locate");
//}
//
///**
// *定位失败后，会调用此函数
// *@param mapView 地图View
// *@param error 错误号，参考CLError.h中定义的错误号
// */
//- (void)didFailToLocateUserWithError:(NSError *)error
//{
//    NSLog(@"location error");
//    NSLog(@"%ld %@ ",(long)error.code,error.domain);
//    
//}

@end

